<template>
  <basic-container>
    <beetles-search :size="'mini'" @search-form="searchChange" @empty-form="searchReset" :expend="false">
      <div slot-scope="{searchConceal}" slot="searchForm" :style="{height:searchConceal? 'auto' :'60px'}"
           style="overflow:hidden">
        <el-form label-width="100px" :model="query" ref="searchForm" :inline="true">
          <el-form-item label="产品名称:">
            <el-input size="mini" v-model="query.name" placeholder="请输入产品名称"></el-input>
          </el-form-item>
          <el-form-item label="客户名称:" v-show="userInfo.is_agency === 1">
            <el-input size="mini" v-model="query.customerName" placeholder="请输入客户名称"></el-input>
          </el-form-item>
          <el-form-item label="操作系统">
            <el-select v-model="query.os" placeholder="请选择操作系统" size="mini">
              <el-option
                label="Android"
                value="1">
              </el-option>
              <el-option
                label="IOS"
                value="2">
              </el-option>
              <el-option
                label="Website"
                value="3">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="类型:">
            <el-input size="mini" v-model="query.category" placeholder="请输入类型"></el-input>
          </el-form-item>
          <el-form-item label="三方平台:">
            <el-select v-model="query.mmpOwned" placeholder="请选择类型" size="mini">
              <el-option v-for="item in thirdPlatform" :key="item.value" :label="item.label"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="三方时区:">
            <el-select v-model="query.timezoneName" filterable placeholder="请选择类型" size="mini">
              <el-option v-for="item in allTimeZone" :label="item.label" :key="item.label"
                         :value="item.label"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="配置人:">
            <el-select v-model="query.configureUserId" placeholder="请选择配置人" size="mini" filterable>
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.realName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="最近配置时间:">
            <el-date-picker
              v-model="query.datetimerange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              value-format="yyyy-MM-dd"
              unlink-panels
              size="mini"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>
    </beetles-search>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :view-name="'appManager'"
               :page.sync="page"
               :row-class-name-rollback="getRowClassName"
               v-model="form"
               ref="crud"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad"
    >
      <!--      :permission="permissionList"-->
      <!--      <template slot-scope="{row}" slot="logoUrl">-->
      <!--        <img :src="row.logoUrl" alt="" style="width: 50px">-->

      <!--      </template>-->
      <template slot="menuLeft" slot-scope="{size}">
        <el-button id="id-business-appmanager-handleAdd"
                   type="primary"
                   size="small"
                   icon="el-icon-plus"
                   plain
                   @click="handleAdd">新 增
        </el-button>
        <el-button id="id-business-appmanager-handleDelete"
                   type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot="os" slot-scope="scope">
        <div style="cursor:pointer;color: #66b1ff" @click="pageTurn(scope.row.appUrl)">
          {{ scope.row.os === 1 ? 'android' : scope.row.os === 2 ? 'ios' : scope.row.os === 3 ? 'website' : '' }}
        </div>
      </template>
      <!--      <template slot="logo" slot-scope="scope">-->
      <!--        <div style="display: flex">-->
      <!--          <img :src="scope.row.logo" alt="" style="height:auto;width: 50px">-->
      <!--        </div>-->
      <!--      </template>-->
      <template slot-scope="{row}" slot="menu" style="display: flex;flex-wrap: wrap">
        <el-tooltip class="item" effect="dark" content="查看" placement="top-start">
          <el-button id="id-business-appmanager-handleCheck"
                     icon="el-icon-view" size="mini" type="text"
                     @click="handleCheck(row)">
          </el-button>
        </el-tooltip>
        <el-tooltip :disabled="row.hasEditPer===0" :class="row.hasEditPer===0?'grey':''" class="item" effect="dark"
                    :content="row.hasEditPer === 0?'无法编辑':'编辑'" placement="top-start">
          <el-button id="id-business-appmanager-handleEdit" icon="el-icon-edit" size="mini" type="text"
                     @click="handleEdit(row,row.hasEditPer)">
          </el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="媒体事件" placement="top-start">
          <el-button :class="row.hasEventPer===0?'grey':''" id="id-business-appmanager-media-event"
                     icon="el-icon-s-operation" size="mini" type="text"
                     @click="openMediaEvent(row,row.hasEventPer)">
          </el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="跟踪配置" placement="top-start">
          <el-button id="id-business-appmanager-handleThirdparty" icon="el-icon-setting" size="mini" type="text"
                     @click="handleThirdparty(row)">
          </el-button>
        </el-tooltip>
        <el-tooltip :disabled="row.hasDelPer=== 0" class="item" :class="row.hasDelPer===0?'grey':''"
                    effect="dark" :content="row.hasDelPer===0?'无法使删除':'删除'" placement="top-start">
          <el-button id="id-business-appmanager-rowDel" :class="row.hasDelPer===0?'grey':''" icon="el-icon-delete"
                     size="mini" type="text"
                     @click="rowDel(row.id,row.hasDelPer)">
          </el-button>
        </el-tooltip>
      </template>

    </avue-crud>

    <!--新增/详情 弹窗-->
    <el-dialog :title="title" :visible.sync="addDialogVisible" append-to-body width="60%"
               :close-on-click-modal="false" :before-close="handleClose" :close="handleClose" >
      <el-form ref="addForm" :model="dialogForm" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col v-if="is_agency === 1" :span="20">
            <el-form-item label="客户:" prop="customerId">
              <el-select id="id-business-appmanager-dialogForm-customerId" :disabled="title === '详情'" size="mini"
                         style="width: 100%" filterable
                         v-model="dialogForm.customerId">
                <el-option v-for="item in customerList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!--          <el-col v-if="title === '详情'" :span="12">-->
          <!--            <div class="check-img-box">-->
          <!--              <img :src="dialogForm.logoUrl" class="check-img">-->
          <!--            </div>-->
          <!--          </el-col>-->
        </el-row>
        <el-row>
          <el-form-item>
            <el-radio-group v-model="dialogForm.isWebsite" :disabled="title==='详情'" @change="websiteControl">
              <el-radio :label="false">商店 URL</el-radio>
              <el-radio :label="true">website URL</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="21">
            <el-form-item label="商店URL:" style="width: 98%" prop="appUrl">
              <el-input id="id-business-appmanager-dialogForm-appUrl"
                        type="textarea" :disabled="title === '详情'" size="mini"
                        v-model="dialogForm.appUrl"></el-input>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="3">-->
          <!--            <el-button v-if="!dialogForm.isWebsite" type="success" :loading="urlLoading" @click="urlConfim">校验</el-button>-->
          <!--          </el-col>-->
        </el-row>
        <!--        <el-row>-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="产品名称:" prop="name" style="width: 100%;">-->
        <!--              <el-input v-model="dialogForm.name"></el-input>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="包名:" prop="name" style="width: 100%;">-->
        <!--              <el-input v-model="dialogForm.name"></el-input>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
        <!--        <el-row>-->
        <!--          <el-form-item label="展示监测URL（Tictok）:" style="width: 90%" prop="impressionMonitorUrl">-->
        <!--            <el-input id="id-business-appmanager-dialogForm-impressionMonitorUrl"-->
        <!--                      type="textarea" :disabled="title === '详情'" size="mini"-->
        <!--                      v-model="dialogForm.impressionMonitorUrl"></el-input>-->
        <!--          </el-form-item>-->
        <!--        </el-row>-->
        <!--        <el-row>-->
        <!--          <el-form-item label="点击监测URL（Tictok）:" style="width: 90%" prop="clickMonitorUrl">-->
        <!--            <el-input id="id-business-appmanager-dialogForm-clickMonitorUrl"-->
        <!--                      type="textarea" :disabled="title === '详情'" size="mini"-->
        <!--                      v-model="dialogForm.clickMonitorUrl"></el-input>-->
        <!--          </el-form-item>-->
        <!--        </el-row>-->
        <el-row :gutter="20" v-if="title==='详情' || dialogForm.isWebsite || formDisable || title==='编辑'">
          <el-col :span="12">
            <el-form-item label="产品名称:" prop="name">
              <el-input id="id-business-appmanager-dialogForm-name" size="mini"
                        :disabled="title === '详情'" v-model="dialogForm.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="包名:">
              <el-input size="mini" id="id-business-appmanager-dialogForm-appPackageId"
                        :disabled="title === '详情'"
                        v-model="dialogForm.appPackageId"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20"  v-if="title==='详情' || dialogForm.isWebsite || formDisable || title==='编辑'">
          <el-col :span="12"  v-if="title === '详情' || dialogForm.isWebsite || (title==='编辑' && dialogForm.isWebsite)"  >
            <el-form-item label="操作系统:">
              <el-input id="id-business-appmanager-dialogForm-os" size="mini" :disabled="true"
                        :value="dialogForm.os === 1 ? 'Android' : (dialogForm.os === 2 ? 'IOS' : 'Website')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型:">
              <el-input id="id-business-appmanager-dialogForm-category" size="mini"
                        :disabled="title === '详情'" v-model="dialogForm.category"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!dialogForm.isWebsite && title==='新增'">
            <el-form-item label="操作系统:">
              <el-select v-model="dialogForm.os1" size="mini" placeholder="请选择">
                <el-option
                  v-for="item in osList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if=" (title==='编辑' && !dialogForm.isWebsite)">
            <el-form-item label="操作系统:">
              <el-select v-model="dialogForm.os" size="mini" placeholder="请选择">
                <el-option
                  v-for="item in osList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="(title==='新增' && !dialogForm.isWebsite) && formDisable" >
          <el-col :span="12">
            <el-form-item label="上传图标:">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :http-request="uploadQiniuCloud"
                :before-upload="beforeAvatarUpload"
                list-type="picture">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-upload2"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <div style="display: flex;justify-content:flex-end;margin-right: 50px">
          <el-button v-if="title==='新增' && !dialogForm.isWebsite && !saveAppDiaable" type="success" :loading="urlLoading" @click="urlConfim">校验</el-button>
          <el-button id="id-business-appmanager-saveApp"
                     v-if="(title !== '详情' && (dialogForm.isWebsite || saveAppDiaable) ) || title==='编辑' " type="primary" size="mini" icon="el-icon-circle-plus-outline"
                     :loading="addLoading"
                     @click="saveApp">保 存
          </el-button>
          <el-button id="id-business-appmanager-dialogForm-handleClose" size="mini" @click="handleClose">取 消</el-button>
        </div>
      </el-form>
    </el-dialog>

    <!--    编辑-->
    <!--    <el-dialog-->
    <!--      append-to-body-->
    <!--      title="编辑"-->
    <!--      :visible.sync="dialogVisible"-->
    <!--      width="30%"-->
    <!--      :before-close="handleClose">-->
    <!--      <span>这是一段信息</span>-->
    <!--      <span slot="footer" class="dialog-footer">-->
    <!--    <el-button @click="dialogVisible = false">取 消</el-button>-->
    <!--    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>-->
    <!--  </span>-->
    <!--    </el-dialog>-->

    <!-- 跟踪配置 -->
    <el-dialog :visible.sync="thirdpartyDialogVisible" append-to-body width="50%"
               :close-on-click-modal="false" :before-close="handleThirdpartyClose">
      <el-form ref="thirdPartyForm" :model="thirdPartyForm" :rules="thirdPartyRules" label-width="120px">
        <el-row>
          <el-form-item label="App URL:">
            {{ thirdPartyForm.appUrl }}
          </el-form-item>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="三方跟踪平台:" prop="mmpOwned">
              <el-select id="id-business-appmanager-getButton" size="mini" style="width: 100%"
                         v-model="thirdPartyForm.mmpOwned"
                         @change="mmpOwnedChenge">
                <el-option v-for="item in thirdPlatform" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-checkbox v-model="thirdPartyForm.isTrack" :true-label="1" :false-label="0">开启三方事件数据拉取</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="时区:" prop="timezoneName">
              <el-select id="id-business-appmanager-thirdPartyForm-timezoneName" style="width: 100%" size="mini"
                         filterable clearable v-model="thirdPartyForm.timezoneName">
                <el-option v-for="item in timezoneList" :label="item.label" :key="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" v-if="thirdPartyForm.mmpOwned === 0 ">
            <el-form-item label="App Token:" prop="adjustAppToken">
              <el-input id="id-business-appmanager-thirdPartyForm-adjustAppToken"
                        v-model="thirdPartyForm.adjustAppToken" size="mini" @input="changeAppToken"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="thirdPartyForm.mmpOwned !== '' ">
            <div style="margin-left: 120px;padding-top: 6px">
              <el-button id="id-business-appmanager-getThirdPermissionList" size="mini" type="primary"
                         :loading="tableLoading"
                         @click="getThirdPermissionList">获取授权事件
              </el-button>
            </div>
          </el-col>
        </el-row>
        <el-row v-if="getButton">
          <el-table :data="thirdPermissionList" stripe style="width: 90%;margin: 0 auto;" v-loading="tableLoading">
            <el-table-column prop="sdkEventName" label="SDK 事件名称">
              <template slot-scope="scope">
                <el-select id="id-business-appmanager-changeToken" style="width: 100%" size="mini"
                           v-model="scope.row.sdkEventName"
                           @change="changeToken($event,scope.$index)" @visible-change="filterSDK">
                  <el-option v-for="(item,index) in sdkChoiceList" :key="index" :label="item.label"
                             :value="item.label"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column v-if="thirdPartyForm.mmpOwned === 0" prop="adjustEventToken"
                             label="Adjust事件token"></el-table-column>
            <el-table-column prop="localEventTag" label="beetles事件名">
              <template slot-scope="scope">
                <el-select id="id-business-appmanager-changeBeetles" style="width: 100%" size="mini"
                           v-model="scope.row.localEventTag"
                           @change="changeBeetles($event,scope.$index)" @visible-change="filterBeetles">
                  <el-option v-for="(item,index) in beetlesChoiceList" :key="index" :label="item.value"
                             :value="item.value"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="localEventName" label="beetles事件显示名">
              <template slot-scope="scope">
                <div v-if="!scope.row.modify">{{ scope.row.localEventName }}</div>
                <div v-if="scope.row.modify">
                  <el-input id="id-business-appmanager-localEventName" v-model="scope.row.localEventName"
                            :class="repeat[scope.$index] ? 'error' : 'success'"
                            size="mini"></el-input>
                  <div v-if="repeat[scope.$index]" class="beetlesName_error">显示名有重复</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column>
              <template slot-scope="scope">
                <el-button id="id-business-appmanager-deletePermiesstion" icon="el-icon-delete" type="text"
                           @click="deletePermiesstion(scope)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-button id="id-business-appmanager-addEvent" style="margin-left: 120px;padding-top: 6px;margin-top: 20px"
                   v-if="thirdPartyForm.mmpOwned !== ''&& getButton" :disabled="thirdPermissionList.length >= 12"
                   size="mini" type="primary" icon="el-icon-plus" @click="addEvent">添加事件
        </el-button>
        <div style="display: flex;justify-content:flex-end;margin-right: 50px">
          <el-button id="id-business-appmanager-handleThirdpartyClose" size="mini" @click="handleThirdpartyClose">取 消
          </el-button>
          <el-button id="id-business-appmanager-thirdPartySubmit" size="mini" type="primary" @click="thirdPartySubmit"
                     icon="el-icon-circle-plus-outline"
                     :disabled="appTokenChanged"> {{ appTokenChanged ? '需先获取授权事件' : '保存配置' }}
          </el-button>
        </div>
      </el-form>
    </el-dialog>
    <!--媒体事件-->
    <el-drawer
      title="媒体事件"
      size="60%"
      :visible.sync="mediaEventDrawer"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      ref="drawer"
      :wrapperClosable="false"
      @close="handleCloseDrawer"
    >
      <el-divider></el-divider>
      <cs-drawer-container>
        <el-form class="media-event-form" ref="form" :model="mediaEventForm" label-width="80px" label-position="top">
          <el-form-item>
            <el-switch
              v-model="mediaEventForm.status"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
            <span class="drawer-label">媒体事件数据拉取</span>
          </el-form-item>
          <el-form-item>
            <div slot="label">facebook</div>
            <el-select class="w100" v-model="mediaEventForm.facebook" placeholder="请选择" size="mini"
                       multiple filterable clearable>
              <el-option
                v-for="item in allEventList.facebook"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <div slot="label">bigo</div>
            <el-select class="w100" v-model="mediaEventForm.bigo" placeholder="请选择" size="mini" multiple filterable clearable>
              <el-option
                v-for="item in allEventList.bigo"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <div slot="label">tiktok</div>
            <el-select class="w100" v-model="mediaEventForm.tiktok" placeholder="请选择" size="mini" multiple filterable clearable>
              <el-option
                v-for="item in allEventList.tiktok"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey">
              </el-option>
            </el-select>
          </el-form-item>
          <!--          <el-form-item>
                      <div slot="label">kwai</div>
                      <el-select class="w100" v-model="mediaEventForm.kwai" placeholder="请选择" size="mini" multiple filterable clearable>
                        <el-option
                          v-for="item in allEventList.kwai"
                          :key="item.dictKey"
                          :label="item.dictValue"
                          :value="item.dictKey">
                        </el-option>
                      </el-select>
                    </el-form-item>-->
          <el-form-item>
            <div slot="label">google&nbsp;&nbsp;&nbsp;&nbsp;<el-button type="primary" plain size="mini"
                                                                       v-loading="googleLoading"
                                                                       @click="getGoogleMediaEventList">获取媒体事件
            </el-button>
            </div>
            <el-row :gutter="20">
              <el-col :span="11">媒体事件</el-col>
              <el-col :span="11">事件显示名</el-col>
              <el-col :span="2"></el-col>
            </el-row>
            <el-row :gutter="20" v-for="(item, index) in mediaEventForm.google" :key="index">
              <el-col :span="11">
                <el-select class="w100" v-model="mediaEventForm.google[index]" placeholder="请选择" size="mini" filterable>
                  <el-option
                    v-for="item in allEventList.google"
                    :key="item.dictKey"
                    :label="item.dictValue"
                    :value="item.dictKey">
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="11">
                <el-input class="w100" size="mini" v-model="mediaEventForm.googleName[index]"
                          placeholder="请输入别名"></el-input>
              </el-col>
              <el-col :span="2">
                <el-button icon="el-icon-delete" circle size="mini" @click="delGoogleEvent(index)"></el-button>
              </el-col>
            </el-row>
            <div>
              <!--<el-tooltip class="item" effect="dark" content="请先点击获取媒体事件" placement="top">-->
              <el-link type="primary" @click="addGoogleEvent">+添加事件</el-link>
              <!--</el-tooltip>-->
            </div>
          </el-form-item>
        </el-form>
        <template slot="bottom">
          <el-button type="primary" size="mini" @click="saveMediaEvent" :disabled="submitLoading">保存</el-button>
          <el-button size="mini" @click="mediaEventDrawer=false">取消</el-button>
        </template>
      </cs-drawer-container>
    </el-drawer>
  </basic-container>
</template>

<script>
import {mapGetters} from "vuex";
import {customer} from "@/api/business/offer";
import {
  getList,
  addApp,
  removeApp,
  detail,
  getBaseEvent,
  getEvent,
  getSavedEvent,
  saveEvent,
  getTimezome,
  verifyProductUrl,
  getAllTimezome, getDictionaryTree, saveEventPlatform, querySavedEventPlatform, queryGoogleMediaEvent
} from "@/api/business/appManager";
import func from "../../util/func";
import error from "../monitor/log/error";
import BeetlesTable from "@/components/basic-components/beetles-table";
import {findObject} from "@/util/util";
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";
import {getSysDictList} from "@/api/system/dict";
import beetlesSearch from "@/components/basic-components/beetles-search"
import {getAllUser} from "@/api/user";
import * as qiniuTools from "@/util/qinnu_upload";

let USER_INF = {}
export default {

  name: "appManager",
  components: {
    BeetlesTable,
    CsDrawerContainer,
    beetlesSearch
  },
  data() {
    let validateEventName = (rule, value, callback) => {
      if (value) {
        this.beetlesList.map(item => {
          if (item.value === value) {
            return callback(new Error('beetles列表中已有相同的显示名!'))
          }
        })
      } else {
        callback();
      }
    };
    let validateAppUrl = (rule, value, callback) => {
      value = (value != null) ? value.trim() : '';
      if (value == '') {
        if (this.dialogForm.isWebsite) {
          return callback(new Error('请输入Website Url'));
        } else {
          return callback(new Error('请输入商店 Url'));
        }
      } else if (!this.dialogForm.isWebsite) {
        let prefixList = [
          'https://play.google.com/',
          'https://apps.apple.com/',
          'http://play.google.com/',
          'http://apps.apple.com/',
        ];
        for (let i = 0; i < prefixList.length; i++) {
          if (value.startsWith(prefixList[i])) {
            if (value == prefixList[i]) {
              break;
            }
            return callback();
          }
        }
        return callback(new Error('非谷歌或苹果商店URL'));
      }
      callback();
    };
    return {
      osList:[
        {value: 1,label:'Android'},
        {value: 2,label:'ios'},
        {value: 3,label:'website'}
      ],
      formDisable:false,
      dialogVisible:true,
      imageUrl:'',
      is_agency: '',
      data: [],
      currOpRowId: '',
      query: {},
      loading: false,
      title: '',
      saveAppDiaable:false,
      appUrlConfirm:true,
      urlLoading:false,
      addDialogVisible: false,//新增弹窗
      thirdpartyDialogVisible: false,//三方配置
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      appTokenChanged: false,//apptoken 发生改变
      form: {},
      addLoading: false,//   新增/修改 加载
      thirdPlatform: [
        {label: 'adjust', value: 0,},
        {label: 'appsflyer', value: 1,}
      ],
      sdkList: [],
      tableLoading: false,
      beetlesList: [],
      websiteHisAppUrl: '',
      normalHisAppUrl: '',
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        delBtn: false,
        menuWidth: 180,
        editBtn: false,
        selection: true,
        dialogClickModal: false,
        selectable: (row, index) => {
          return row.hasDelPer === 1
        },
        column: [
          {
            label: '产品名称',
            prop: "name",
            rules: [{
              required: true,
              message: "请输入公司名称",
              trigger: "blur"
            }],
            // search: true,
          },
          {
            label: "操作系统",
            prop: "os",  //1 android / 2 ios
            width: 70,
          },
          // {
          //   label: "logo",
          //   prop: "logoUrl",
          // },
          {
            label: "包名",
            prop: "appPackageId",
          },
          {
            label: "客户名称",
            prop: "customerName",
            // search: true,
          },
          {
            label: "类型",
            prop: "category",
            type: 'switch',
            addDisplay: false,
            dicData: [
              {label: '', value: 0},
              {label: '', value: 1}
            ]
          },
          {
            label: '三方平台',
            prop: 'mmpOwned',
            type: 'select',
            dicData: [
              {label: '暂无配置', value: -1},
              {label: 'adjust', value: 0},
              {label: 'appsflyer', value: 1},
            ],
          },
          {
            label: '三方时区',
            prop: 'timezoneName',
            dataType: 'string',
            type: 'select',
            dicData: [],

          },
          {
            label: '最近配置人',
            prop: 'configureUser',
          },
          {
            label: '最近配置时间',
            prop: 'configureTime',
          },
        ]
      },
      get_SDK_Fail: false,//获取去sdk失败
      dialogForm: { //form表单值
        customerId: null,
        isWebsite: false,
        appUrl: null,
        impressionMonitorUrl: null,
        clickMonitorUrl: null,
        name: null,
        os:null,
        os1: 2,
        // logoUrl: null,
        appPackageId: null,
        category: null,
      },
      thirdPartyForm: {
        appId: '',
        id: '',
        appUrl: '',
        mmpOwned: '',
        isTrack: false,
        adjustAppToken: null,
        oldmmpOwned: '',
        oldAdjustAppToken: '',
        timezoneName: '',
      },//第三方表单
      thirdPermissionList: [],//第三方权限列表
      timezoneList: [],//时区列表
      timezone: [],
      appsflyerTimezone: [],
      getButton: false,
      customerList: [],//客户列表
      sdkChoiceList: [], //能选中的sdk列表
      beetlesChoiceList: [],//能选中的beetles列表
      repeat: [],//重复对象
      rules: {
        appUrl: {required: true, validator: validateAppUrl, trigger: 'blur'},
        customerId: {required: true, message: '请选择客户', trigger: 'change'},
        name: {required: true, message: '请输入app名称', trigger: 'blur'}
      },
      tableRules: {
        localEventName: [{required: true, validator: validateEventName, trigger: 'blur'}]
      },
      thirdPartyRules: {
        mmpOwned: [{required: true, message: '请选择三方跟踪平台', trigger: 'change'}],
        timezoneName: [{required: true, message: '请选择时区', trigger: 'change'}],
        adjustAppToken: [{required: true, message: '请输入App Token', trigger: 'blur'}]
      },
      // marco
      // 媒体事件
      mediaEventDrawer: false,
      mediaEventForm: {
        status: 1,
        facebook: [],
        google: [],
        googleName: [],
        bigo: [],
        tiktok:[],
        kwai:[]
      },
      // 媒体列表
      platformsList: [],
      // 事件列表
      allEventList: {
        facebook: [],
        google: [],
        bigo: [],
      },
      // 搜索事件标识
      queryEventKey: {
        facebook: 'facebook_event_node',
        bigo: 'bigo_event_node',
        tiktok: 'tiktok_event_node',
        kwai: 'kwai_event_node'
      },
      // 当前app
      currentApp: null,
      userList: [], // 用户列表
      // 所有时区
      allTimeZone: [],
      // 获取谷歌事件loading
      googleLoading: false,
      // 提交loading
      submitLoading: false

    }
  },
  computed: {
    ...mapGetters(["permission", "userInfo"]),
    finalMediaEventFrom() {
      const finalData = {
        appId: this.currentApp.id,
        status: this.mediaEventForm.status,
        facebook: [],
        bigo: [],
        google: [],
        tiktok:[],
        kwai:[]
      }
      if (this.mediaEventForm.facebook.length > 0) {
        finalData.facebook = this.allEventList.facebook.filter(item => this.mediaEventForm.facebook.includes(item.dictKey)).map(item => {
          return {
            sdkEventName: item.dictKey,
            localEventName: item.dictValue,
          }
        })
      }
      if (this.mediaEventForm.bigo.length > 0) {
        finalData.bigo = this.allEventList.bigo.filter(item => this.mediaEventForm.bigo.includes(item.dictKey)).map(item => {
          return {
            sdkEventName: item.dictKey,
            localEventName: item.dictValue,
          }
        })
      }
      if (this.mediaEventForm.tiktok.length > 0) {
        finalData.tiktok = this.allEventList.tiktok.filter(item => this.mediaEventForm.tiktok.includes(item.dictKey)).map(item => {
          return {
            sdkEventName: item.dictKey,
            localEventName: item.dictValue,
          }
        })
      }
      if (this.mediaEventForm.kwai.length > 0) {
        finalData.kwai = this.allEventList.kwai.filter(item => this.mediaEventForm.kwai.includes(item.dictKey)).map(item => {
          return {
            sdkEventName: item.dictKey,
            localEventName: item.dictValue,
          }
        })
      }
      if (this.mediaEventForm.google.length > 0) {
        this.mediaEventForm.google.forEach((item, index) => {
          if (item !== '') {
            finalData.google.push(
              {
                sdkEventName: item,
                localEventName: this.mediaEventForm.googleName[index],
              }
            )

          }
        })
      }

      // const selectedEvent = [] // 选择的事件
      // const status = this.mediaEventForm.pullData // 拉取状态
      // // 筛选选中的媒体事件KEY值
      // for (let key in this.mediaEventForm.selectEvent) {
      //   if (this.mediaEventForm.selectEvent[key].length > 0) {
      //     selectedEvent.push(...this.mediaEventForm.selectEvent[key])
      //   }
      // }
      // for (let key in this.allEventList) {
      //   if (this.allEventList[key].length > 0) {
      //     this.allEventList[key].forEach(item => {
      //       if (selectedEvent.includes(item.dictKey))
      //         finalData.details.push({
      //           status,
      //           appId: this.currentAppId,
      //           sdkEventName: item.dictKey,
      //           localEventName: item.dictValue,
      //           eventPlatform: key
      //         })
      //     })
      //   }
      // }
      return finalData
    }
  },
  async created() {
    //获取客户列表
    customer().then(res => {
      this.customerList = res.data.data
    })
    //获取时区
    this.getTimezone();
    // 查找媒体列表
    await this.getPlatformsList()
    await this.getEventList()
    getAllUser({statusList: '0,1,2'}).then(res => {
      this.userList = res.data.data
    });
  },

  mounted() {
    if (this.userInfo.is_agency === 0)
      this.option.column.splice(this.option.column.findIndex(it =>
        it.prop === 'customerName'), 1)
  },
  methods: {
    urlConfim() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          // if (this.dialogForm.customerId === null) {
          //   this.$message.warning('请先选择客户')
          //   return
          // }
          this.urlLoading = true
          verifyProductUrl({customerId: this.dialogForm.customerId, appUrl: this.dialogForm.appUrl}).then(res => {
            console.log(res)
            this.$message.success('保存成功')
            this.urlLoading = false
            this.addDialogVisible = false
          }).catch(() => {
            // this.$message.error('校验失败,请再次点击保存')
            // this.dialogForm.name = 'unknow'
            this.formDisable = true
            this.urlLoading = false
            this.saveAppDiaable = true
          })
        } else {
          return false
        }
      })
    },
    uploadQiniuCloud(file) {
      const that = this
      const fileData = qiniuTools.getFileData(file)
      const callback = {
        next(res) {
        },
        error(err) {
          this.$message.error("上传图片失败! err => " + err);
        },
        complete(res) {
          const url = 'http://' + fileData.server + '/' + res.key
          that.$set(that, 'imageUrl', url)
          // that.logoUrl = url
        }
      }
      const uploader = qiniuTools.uploadQiniuCloud(file, fileData)
      uploader.subscribe(callback)
    },
    beforeAvatarUpload(file) {
      var img = file.name.substring(file.name.lastIndexOf('.') + 1)
      const suffix = img === 'jpg'
      const suffix2 = img === 'png'
      const suffix3 = img === 'jpeg'
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!suffix && !suffix2 && !suffix3) {
        this.$message.error("只能上传图片！");
        return false
      }
      // 可以限制图片的大小
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!');
      }
      return suffix || suffix2 || suffix3
    },
    mmpOwnedChenge(val) {
      this.timezoneList = this.timezone[this.thirdPlatform[val].label]
      this.thirdPartyForm.timezoneName = ''
      this.getButton = false;
    },
    websiteControl() {
      if (this.dialogForm.isWebsite) {
        this.normalHisAppUrl = this.dialogForm.appUrl
        this.dialogForm.appUrl = this.websiteHisAppUrl
      } else {
        this.websiteHisAppUrl = this.dialogForm.appUrl
        this.dialogForm.appUrl = this.normalHisAppUrl
      }
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange() {
      this.query.startDate = this.query.datetimerange ? this.query.datetimerange[0] : null
      this.query.endDate = this.query.datetimerange ? this.query.datetimerange[1] : null
      let params = this.query;
      // delete params.datetimerange
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    /**
     * 分页
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 列表行数修改回调方法
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * 点击刷新按钮的回调方法
     */
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * 获取列表数据
     */
    onLoad(page, params = {}) {
      this.loading = true;

      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     * 新增窗口
     */
    handleAdd() {
      this.dialogForm = { //form表单值
        customerId: null,
        isWebsite: false,
        appUrl: null,
        impressionMonitorUrl: null,
        clickMonitorUrl: null,
        name: null,
        os:null,
        os1: 2,
        // logoUrl: null,
        appPackageId: null,
        category: null,
      };
      this.addDialogVisible = true;
      this.title = '新增'
      this.dialogForm.os1 = 2
      this.is_agency = this.userInfo.is_agency
      this.saveAppDiaable = false
      this.formDisable = false
      this.imageUrl=''

      // this.reset()
    },
    /**
     * 删除
     */
    handleDelete() {
      if (this.selectionList.length < 1) {
        return
      }
      let deleteIds = [];
      this.selectionList.forEach(ele => {
        if (ele.hasDelPer !== 0) {
          deleteIds.push(ele.id);
        }
      });
      if (deleteIds.length === 0) {
        this.$message.warning("请选择至少一条允许删除的客户数据");
        return;
      }

      // 不允许删除
      let noDeleteIds = [];
      this.selectionList.forEach(ele => {
        if (ele.hasDelPer === 0) {
          noDeleteIds.push(ele.id);
        }
      });
      if (noDeleteIds.length > 0 && this.selectionList.length > 1) {
        this.$message.warning("列表包含有已关联订单或已配置三方平台的APP,请重新选择！");
        return;
      }



      this.$confirm('此操作将删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = []
        this.selectionList.map(item => {
          data.push(item.id)
        })
        data = data.join(',')
        removeApp(data).then(res => {
          if (res.data.data) {
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
            this.onLoad(this.page)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    /**
     * 行内删除
     * @param id
     */
    rowDel(id, val) {
      if (val === 0) {
        this.$message.error("该App已关联了订单，所以无法删除APP。")
      } else {
        this.$confirm('此操作将删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data = []
          data.push(id)
          data = data.join(',')
          removeApp(data).then(res => {
            if (res.data.data) {
              this.$message({
                type: 'success',
                message: '删除成功！'
              })
              this.onLoad(this.page)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

      }

    },
    /**
     * 关闭弹窗
     */
    handleClose() {
      this.addDialogVisible = false;
      this.addLoading = false
      this.reset()
      this.onLoad(this.page)
      this.imageUrl = ''
      this.formDisable = false
    },
    /**
     * 详情
     */
    handleCheck(row) {
      console.log(row)
      this.currOpRowId = row.id;
      this.addDialogVisible = true;
      this.title = '详情'
      this.is_agency = this.userInfo.is_agency
      // this.reset()
      this.dialogForm = row
      this.dialogForm.isWebsite = row.os !== '' ? (row.os === 3 ? true : false) : null;
      //this.dialogForm.os = row.os === 1 ? 'android' : row.os === 2 ? 'ios' : row.os === 3 ? 'website' : '';
    },
    reset() {
      this.websiteHisAppUrl = ''
      this.normalHisAppUrl = ''
      this.dialogForm = {
        customerId: null,
        isWebsite: false,
        appUrl: null,
        name: null,
        os: null,
        // logoUrl: null,
        appPackageId: null,
        category: null,
      }
    },
    /**
     * 编辑
     */
    handleEdit(row, val) {
      if (val === 0) {
        this.$message.error("该App已关联订单或完成跟踪配置，所以不能编辑")
      } else {
        this.currOpRowId = row.id;
        this.addDialogVisible = true;
        this.title = '编辑'
        this.is_agency = this.userInfo.is_agency
        this.reset()
        this.dialogForm = row
        this.dialogForm.isWebsite = row.os !== '' ? (row.os === 3 ? true : false) : null
      }
    },
    /**
     * 三方配置弹窗
     */
    handleThirdparty(row) {
      this.currOpRowId = row.id;
      detail(row.id).then(res => {
        this.thirdPartyForm = {
          appId: row.id,
          id: res.data.data.id,
          appUrl: res.data.data.appUrl,
          isTrack: res.data.data.isTrack,
          mmpOwned: res.data.data.mmpOwned == '-1' ? '' : res.data.data.mmpOwned,
          adjustAppToken: res.data.data.adjustAppToken,
          timezoneName: res.data.data.timezoneName == '-1' ? '' : res.data.data.timezoneName,
        }
        if (this.thirdPartyForm.mmpOwned !== '') {
          this.thirdPartyForm.oldmmpOwned = this.thirdPartyForm.mmpOwned;
          this.mmpOwnedChenge(this.thirdPartyForm.mmpOwned)
          this.thirdPartyForm.timezoneName = res.data.data.timezoneName == '-1' ? '' : res.data.data.timezoneName
          if (this.thirdPartyForm.adjustAppToken !== '') {
            this.thirdPartyForm.oldAdjustAppToken = this.thirdPartyForm.adjustAppToken
          }
          this.getThirdPermissionList()
        }
      })
      this.thirdpartyDialogVisible = true
      //获取数据
    },
    /**
     * 获取权限列表
     */
    getThirdPermissionList() {
      if (this.thirdPartyForm.mmpOwned === 0 && !this.thirdPartyForm.adjustAppToken) {
        this.$message({
          type: 'error',
          message: '拉取adjust授权事件,需要输入App Token'
        })
        return
      }
      let oldThirdPermissionList
      //如果adjust Token 发生改变 保留之前thirdPermissionList的数据
      if (this.thirdPartyForm.adjustAppToken !== this.thirdPartyForm.oldAdjustAppToken && this.thirdPartyForm.oldAdjustAppToken && this.thirdPartyForm.mmpOwned === 0) {
        /*this.$confirm('系统检测出最新获取的授权事件已发生变更,系统将自动删除部分匹配不上的SDK事件,请知悉!', '重要通知!', {
          confirmButtonText: '确定',
          type: 'warning',
          showCancelButton: false,
        })*/
        oldThirdPermissionList = this.thirdPermissionList
      }
      this.get_SDK_Fail = false
      this.appTokenChanged = false
      this.getButton = true
      this.sdkList = []
      this.beetlesList = []
      this.thirdPermissionList = []

      //获取sdk列表
      this.getSdk(() => {
        this.getBeetlesList();
        this.getEvent(oldThirdPermissionList);
      })

      this.thirdPermissionList.map(item => {
        if (item.localEventName === '') {
          item['modify'] = true
        } else {
          item['modify'] = false
        }
      })
    },

    /**
     * 获取sdk列表
     */
    getSdk(callback) {
      this.tableLoading = true
      getEvent(this.thirdPartyForm.id, this.thirdPartyForm.mmpOwned, this.thirdPartyForm.adjustAppToken).then(res => {
        this.sdkList = res.data.data
        this.sdkChoiceList = [...res.data.data]
        //获取 thirdPermissionList
        callback();
      }, error => {
        if (error) {
          this.get_SDK_Fail = true
          this.tableLoading = false
          callback();
        }
      })
    },
    /**
     * 获取beetles列表
     */
    getBeetlesList() {
      // 获取beetles列表
      getBaseEvent().then(res => {
        this.beetlesList = res.data.data
        this.beetlesChoiceList = [...res.data.data]
      })

    },
    /**
     * 获取事件列表
     */
    getEvent(oldList) {
      this.tableLoading = true
      getSavedEvent(this.thirdPartyForm.appId).then(res => {
        if (res.data.data) {
          //切换 token
          if (!this.get_SDK_Fail && this.thirdPartyForm.adjustAppToken !== this.thirdPartyForm.oldAdjustAppToken &&
            this.thirdPartyForm.mmpOwned == 0 && this.thirdPartyForm.oldmmpOwned !== '' && this.thirdPartyForm.oldAdjustAppToken) {
            this.thirdPermissionList = this.changeTokenBackPermissionList(oldList, res.data.data);
            this.tableLoading = false
            if (this.thirdPermissionList.length < 1) {
              this.addEvent()
            }
          } else
            //切换平台
          if (this.thirdPartyForm.oldmmpOwned !== '' && !(this.thirdPartyForm.mmpOwned === this.thirdPartyForm.oldmmpOwned)) {
            this.thirdPermissionList = [];
            this.tableLoading = false;
          } else {
            this.thirdPermissionList = res.data.data
            this.tableLoading = false;
          }
          //如果 列表没有值添加一条空白数据
          if (this.thirdPermissionList.length < 1) {
            this.addEvent()
          } else if (this.get_SDK_Fail) {
            this.thirdPermissionList.map(item => {
              //adjust
              if (this.thirdPartyForm.mmpOwned === 0) {
                this.sdkList.push({label: item.sdkEventName, value: item.adjustEventToken})
              }
              //appsflyer
              if (this.thirdPartyForm.mmpOwned === 1) {
                this.sdkList.push({label: item.sdkEventName, value: item.sdkEventName})
              }
            })
            this.sdkChoiceList = [...this.sdkList]
          }
        }
      }, (error) => {
        if (error)
          this.tableLoading = false
      })
    },

    /**
     * 获取时区列表
     */
    getTimezone() {
      //获取时区列表
      getAllTimezome().then(res => {
        if (res.data.data) {
          this.timezone = res.data.data
          this.allTimeZone = [...res.data.data.adjust, ...res.data.data.appsflyer]
          let column = findObject(this.option.column, 'timezoneName', 'prop')
          if (column != null) {
            this.appsflyerTimezone = this.timezone['appsflyer'];
            column.dicData = this.appsflyerTimezone;
          }
        }
      })
    },

    /**
     * adjust token 切换是保留在新token下 sdk包含的数据
     */
    changeTokenBackPermissionList(oldList, newList) {
      let data = []
      oldList.map(item => {
        this.sdkList.map(i => {
          if (item.sdkEventName === i.label) {
            if (newList.findIndex(it => {
              it.sdkEventName === item.sdkEventName
            }) === -1) {
              data.push(item)
            }
          }
        })
      })

      if (data.length !== oldList.length) {
        this.$confirm('系统检测出最新获取的授权事件已发生变更,系统将自动删除部分匹配不上的SDK事件,请知悉!', '重要通知!', {
          confirmButtonText: '确定',
          type: 'warning',
          showCancelButton: false,
        })
      }
      return data
    },

    /**
     * 添加列表
     */
    addEvent() {
      this.thirdPermissionList.push(this.thirdPartyForm.mmpOwned === 0 ?
        {sdkEventName: '', localEventTag: '', localEventName: '', adjustEventToken: '', modify: true}
        : {sdkEventName: '', localEventTag: '', localEventName: '', modify: true})
    },
    /**
     * 当平台为adjust时 修改sdk的同时 修改token
     */
    changeToken(val, index) {
      this.sdkList
      if (this.thirdPartyForm.mmpOwned === 0) {
        this.thirdPermissionList[index].adjustEventToken = this.sdkList.filter(item => item.label == val)[0].value
      }
    },
    deletePermiesstion(row) {
      this.thirdPermissionList.splice(row.$index, 1)
    },
    /**
     *
     */
    changeBeetles(val, index) {
      this.thirdPermissionList[index].localEventName = this.beetlesList.filter(item => item.value === val)[0].label
      this.thirdPermissionList[index].modify = this.beetlesList.filter(item => item.value == val)[0].label ? false : true
    },
    /**
     * 新增 编辑App
     */
    saveApp() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.addLoading = true
          let data = {
            appUrl: this.dialogForm.appUrl,
            impressionMonitorUrl: this.dialogForm.impressionMonitorUrl,
            clickMonitorUrl: this.dialogForm.clickMonitorUrl,
            customerId: this.dialogForm.customerId,
            name: this.dialogForm.name,
            os:this.dialogForm.isWebsite ? 3 : this.dialogForm.os,
            // os1:this.dialogForm.os1,
            appPackageId: this.dialogForm.appPackageId,
            isWebsite: this.dialogForm.isWebsite,
            category: this.dialogForm.category,
            imageUrl:this.imageUrl
          }
          if (this.title === '编辑') {
            data['id'] = this.dialogForm.id
          }
          addApp(data).then(res => {
            if (res.data.data) {
              let message = '操作成功';
              if (res.data.msg != null && res.data.msg != '') {
                message = res.data.msg;
              }
              if (this.title === '编辑') {
                this.$message({
                  type: 'success',
                  message: message
                })
              } else {
                this.$message({
                  type: 'success',
                  message: message
                })
              }
              this.addDialogVisible = false;
              this.saveAppDiaable = false
              this.addLoading = false
              this.onLoad(this.page)
              this.reset()
            }
          }).catch(error => {
            if (error) {
              this.addLoading = false
            }
          })
        } else {
          return false
        }
      })

    },
    /**
     * 重置三方配置表单
     */
    resetThridpartyForm() {
      // this.thirdPartyForm = {
      //   appId: '',
      //   id: '',
      //   appUrl: '',
      //   mmpOwned: '',
      //   isTrack: false,
      //   adjustAppToken: null,
      // },//第三方表单
      this.$refs.thirdPartyForm.resetFields()
      this.thirdPermissionList = []
    },
    /**
     * 关闭三方配置
     */
    handleThirdpartyClose() {
      this.thirdpartyDialogVisible = false;
      this.getButton = false;
      this.resetThridpartyForm();
      this.repeat = [];
      this.onLoad(this.page, this.query)
    },
    /**
     * 三方事件保存
     */
    thirdPartySubmit() {
      if (!this.thirdPermissionList.length > 0) {
        this.$message({
          type: 'warning',
          message: '请至少保存一条授权事件!'
        })
        return
      }
      this.$refs.thirdPartyForm.validate(visible => {
        if (visible) {

          if (this.eventComplate() === false)
            return;

          if (this.beetlesNameRepeat())
            return

          let data = {
            appId: this.thirdPartyForm.appId,
            details: this.thirdPermissionList,
            isTrack: this.thirdPartyForm.isTrack,
            mmpOwned: this.thirdPartyForm.mmpOwned,
            appToken: this.thirdPartyForm.adjustAppToken,
            timezoneName: this.thirdPartyForm.timezoneName,
          }

          saveEvent(data).then(res => {
            if (res.data.data) {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.handleThirdpartyClose();
            }
          })
        } else {
          return false
        }
      })

    },
    /**
     * 过滤sdk
     */
    filterSDK() {
      this.sdkChoiceList = [...this.sdkList]
      this.thirdPermissionList.map(item => {
        if (item.sdkEventName !== '') {
          this.sdkChoiceList.splice(this.sdkChoiceList.findIndex(i => i.label === item.sdkEventName), 1)
        }
      })
    },
    /**
     * 过滤beetles
     */
    filterBeetles() {
      this.beetlesChoiceList = [...this.beetlesList]
      this.thirdPermissionList.map(item => {
        if (item.localEventTag !== '') {
          this.beetlesChoiceList.splice(this.beetlesChoiceList.findIndex(i => i.value === item.localEventTag), 1)
        }
      })
    },
    /**
     * 点击操作系统 页面跳转
     */
    pageTurn(url) {
      if (url) {
        window.open(url)
      }
    },
    /**
     * adjust App Token 变化监控
     */
    changeAppToken() {
      if (this.thirdPartyForm.adjustAppToken !== this.thirdPartyForm.oldAdjustAppToken) {
        this.appTokenChanged = true
      } else {
        this.appTokenChanged = false
      }
    },

    /**
     * 判断事件是否填写完整
     */
    eventComplate() {
      let complete = true
      this.thirdPermissionList.map(item => {
        if (this.thirdPartyForm.mmpOwned == 0) {
          if (item.sdkEventName === '' || item.localEventTag === '' || item.localEventName === '' || item.adjustEventToken === '') {
            complete = false
          }
        } else {
          if (item.sdkEventName === '' || item.localEventName === '' || item.localEventTag === '') {
            complete = false
          }
        }
      })
      if (!complete) {
        this.$message({
          type: 'warning',
          message: '请将授权事件填写完整!'
        })
        return complete
      }
      return complete
    },
    /**
     * 判断自定义beeltes显示名 是否有重复
     */
    beetlesNameRepeat() {
      this.repeat = []
      let hasRepeat = false
      this.thirdPermissionList.map((item, index) => {
        this.repeat.push(false)
        if (item.modify === true) {
          if (this.beetlesList.findIndex(val => val.label === item.localEventName) !== -1) {
            this.repeat[index] = true
            hasRepeat = true
          }
          this.thirdPermissionList.map((it, i) => {
            if (it.localEventName === item.localEventName && i !== index) {
              this.repeat[index] = true
              hasRepeat = true
            }
          })
        }
      })
      return hasRepeat
    },
    getRowClassName({row, rowIndex}) {
      if (row.id == this.currOpRowId) {
        return "current-op-row";
      } else {
        return "";
      }
    },
    /**
     * 1. 第一次 新增  平台 空   token 空    adjust               平台 空 token空
     * 2. 切换token  对比  平台不变
     * 3. 切换平台    直接清空
     */
    // marco
    //   打开媒体事件
    async openMediaEvent(row, hasEventPer) {
      if (hasEventPer === 0) return this.$alert(`1.APP已创建订单<br/>2.已绑定账号`, '配置媒体事件需要完成以下步骤', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true
      });
      this.currentApp = row
      // console.log('row', row)
      await this.getCurrentMediaEvent()
      this.mediaEventDrawer = true
    },
    handleCloseDrawer() {
      this.allEventList.google = []
      this.submitLoading = false
    },
    // 获取媒体列表
    async getPlatformsList() {
      const {platforms} = await getSysDictList('platforms')
      this.platformsList = platforms
    },
    // 查询所媒体包含的事件
    async getEventList() {
      for (let key in this.queryEventKey) {
        const {data: res} = await getDictionaryTree({code: this.queryEventKey[key]})
        this.allEventList[key] = res.data
      }
    },
    // 保存媒体事件
    async saveMediaEvent() {
      this.submitLoading = true
      if (this.finalMediaEventFrom.google.findIndex(item => item.localEventName === '') !== -1) {
        this.submitLoading = false
        return this.$message.error('事件显示名不能为空')
      }
      const {data: res} = await saveEventPlatform(this.finalMediaEventFrom).catch(e => {
        this.submitLoading = false
      })
      this.mediaEventDrawer = false
      if (res.code !== 200) return this.$message.error('保存失败')
      this.$message.success('保存成功')
      this.onLoad(this.page)
      // console.log(this.finalMediaEventFrom)
      // 判断谷歌别名不能为空
    },
    // 查询当前媒体事件
    async getCurrentMediaEvent() {
      const {data: res} = await querySavedEventPlatform({appId: this.currentApp.id})
      if (res.code !== 200) return
      const temp = res.data
      // this.mediaEventForm.pullData = res.data.length > 0 ? res.data[0].status : 0
      // console.log('res状态',res.data[0].status)
      this.mediaEventForm.status = res.data.length > 0 ? res.data[0].status : 1
      this.mediaEventForm.facebook = []
      this.mediaEventForm.google = []
      this.mediaEventForm.googleName = []
      this.mediaEventForm.bigo = []
      this.mediaEventForm.tiktok = []
      this.mediaEventForm.kwai = []
      temp.forEach(item => {
        if (item.eventPlatform === 'google') {
          this.mediaEventForm.googleName.push(item.localEventName)
        }
        this.mediaEventForm[item.eventPlatform].push(item.sdkEventName)
      })
    },
    // 获取谷歌媒体事件
    async getGoogleMediaEventList() {
      this.googleLoading = true
      this.$message.info('google媒体事件获取中')
      try {
        const {data: res} = await queryGoogleMediaEvent({
          appPackageId: this.currentApp.appPackageId
        })
        this.googleLoading = false
        if (res.code !== 200) return this.$message.error('获取Google媒体事件失败')
        this.$message.success(res.data.length > 0 ? '获取Google媒体事件成功' : '无Google媒体事件')
        this.allEventList.google = res.data
      } catch (err) {
        this.googleLoading = false
      }

    },
    // 时区回显问题
    handleChange(val) {
      if (val) {    // 操作选中角色发生变化
        this.$set(this.query, this.query.timezoneName, val)
      } else {
        this.$set(this.query, this.query.timezoneName, '')
      }
    },
    // 添加谷歌事件
    addGoogleEvent() {
      if (this.allEventList.google.length===0) return this.$message.warning('无google媒体事件,请先获取媒体事件！')
      this.mediaEventForm.google.push('')
      this.mediaEventForm.googleName.push('')
    },
    delGoogleEvent(index) {
      this.mediaEventForm.google.splice(index, 1)
      this.mediaEventForm.googleName.splice(index, 1)
    }
  }
}

</script>

<style scoped lang="scss">
/deep/ .el-upload--picture{
  width:120px;
  height: 120px;

}
.check-img-box {
  line-height: 100px;
  height: 100px;
  margin-left: 35%;
}

.check-img {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
}

.beetlesName {
  /deep/ .el-form-item {
    margin-bottom: 0;
  }
}

.beetlesName_error {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  position: absolute;
  padding-top: 4px;
}

.error {
  /deep/ .el-input__inner {
    border-color: #f56c6c;
  }
}

.success {
  /deep/ .el-input__inner {
    border-color: #dcdfe6;
  }
}

/deep/ .current-op-row {
  background-color: #f5dab1;
}

.grey {
  color: #808080;
}

.media-event-form {
  padding: 0 25px;

  .drawer-label {
    display: inline-block;
    vertical-align: middle;
    margin-left: 12px;
  }

  .w100 {
    width: 100%;
  }

  .w50 {
    width: 50%;
  }
}

//搜索栏宽度对齐
.el-input {
  width: 192px;
}
.avatar{
  width:120px;
  height: 120px
}
</style>
